package com.zyh.day02

object MapTest {
  def main(args: Array[String]): Unit = {
    //创建
    val tuple: (String, Int) = "xiaoming" -> 30
    var map: Map[String,Int] = Map("xiaohei" -> 18, ("xiaobai", 20), ("xiaohua", 22))//一个kv对象是一个tuple2类型
    println(map)
    //添加
    map += "xiaohong" -> 25
    println(map)
    //删除
    map -= "xiaohong"
    println(map)
    //更新
    map += "xiaohei" -> 30
    map = map.updated("xiaobai",22)
    println(map)
    //获取
    val age: Int = map("xiaohei")//如果key不存在抛异常
    println(s"age = ${age}")

    val option: Option[Int] = map.get("xiaohei")
    val age2: Int = option.get//key不存在时抛异常
    val age3: Int = option.getOrElse(0)//key不存在时返回默认值
    println(s"age2 = ${age2}")
    println(s"age3 = ${age3}")
    val age4: Int = map.getOrElse("xiaohei", 20)//如果key不存在返回默认值
    println(s"age4 = ${age4}")
    //遍历
    for(item <- map) println(s"name,age = ${item._1},${item._2}")
    println("=========================")
    for((k,v) <- map) println(s"k,v = ${k},$v")
  }
}
